package org.alis.smallcc.designpatterns.behavior.proxy.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.alis.smallcc.designpatterns.behavior.proxy.Order;
import org.alis.smallcc.designpatterns.behavior.proxy.db.DataSourceContextHolder;

/**
 * 抽象订单动态代理
 * 
 * @author: luochuan     
 * @date: 2020年11月19日 上午11:18:37
 */
public class OrderServiceDynamicProxy implements InvocationHandler{
	
	private Object obj;
	
	public OrderServiceDynamicProxy(Object obj) {
		this.obj = obj;
	}
	
	@SuppressWarnings("unchecked")
	public <T> T bind() {
		return (T)Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		beforeMethod(args[0]);
		Object invoke = method.invoke(obj, args);
		afterMethod();
		return invoke;
	}
	/**
	 * 方法执行之前进行操作
	 */
	private void beforeMethod(Object args) {
		Integer useId = 0;
		System.out.println("动态代理 before code");
        if(args instanceof Order){
            Order order = (Order)args;
            useId = order.getUserId();
        }
        int dbRouter = useId % 2;
        System.out.println("动态代理分配到【db"+dbRouter+"】处理数据");

        // 设置dataSource
        DataSourceContextHolder.set("db"+dbRouter);
	}
	
	private void afterMethod(){
        System.out.println("动态代理 after code");
    }
	
	
}
